package com.wandousoushu.jiusen.ui.login

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.wandousoushu.jiusen.MainActivity
import com.wandousoushu.jiusen.MyApplication
import com.wandousoushu.jiusen.MyApplication.Companion.instance
import com.wandousoushu.jiusen.R
import com.wandousoushu.jiusen.bean.AdBean
import com.wandousoushu.jiusen.bean.H5AdBean
import com.wandousoushu.jiusen.bean.UserInfo
import com.wandousoushu.jiusen.booksource.data.entities.Book
import com.wandousoushu.jiusen.booksource.model.BookManager
import com.wandousoushu.jiusen.booksource.model.BookSourceManager
import com.wandousoushu.jiusen.booksource.model.SearchBookManager
import com.wandousoushu.jiusen.util.GsonUtils
import com.wandousoushu.jiusen.util.ValidatePhoneUtil
import com.wandousoushu.jiusen.util.putPrefString
import com.wandousoushu.jiusen.web.http.MainHttpConsts
import com.wandousoushu.jiusen.web.http.MainHttpUtils
import kotlinx.android.synthetic.main.activity_login.*
import org.json.JSONArray
import org.json.JSONObject
import java.util.*


class LoginActivity : AppCompatActivity() {
    private var phoneNum: String? = null
    private var pwd: String? = null

    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        val textWatcher: TextWatcher = object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                val phone = edit_phone.getText().toString()
                val pwd = edit_pwd.getText().toString()
                btn_login.setEnabled(!TextUtils.isEmpty(phone) && !TextUtils.isEmpty(pwd))
            }

            override fun afterTextChanged(s: Editable) {}
        }
        edit_phone.addTextChangedListener(textWatcher)
        edit_pwd.addTextChangedListener(textWatcher)
        btn_login.setOnClickListener(View.OnClickListener { Login() })
        btn_register.setOnClickListener(View.OnClickListener {
            val intent = Intent(applicationContext, RegisterActivity::class.java)
            startActivity(intent)
        })
        btn_forget_pwd.setOnClickListener(View.OnClickListener {
            val intent = Intent(applicationContext, RetrievePasswordActivity::class.java)
            startActivity(intent)
        })
        login_ll_back.setOnClickListener(View.OnClickListener { finish() })
        var WXapi = WXAPIFactory.createWXAPI(this, MainHttpConsts.WX_APP_ID, true)
        iv_weixin.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                if (isWXAppInstalledAndSupported()) {  // 用户是否安装微信客户端
                    // send oauth request
                    val req = SendAuth.Req()
                    req.scope = "snsapi_userinfo"
                    val random = Random()
                    val radomData = random.nextInt(100)
                    val state = MainHttpConsts.BaseState + radomData
                    MyApplication.instance.wxLoginState=state
                    req.state = state
                    WXapi!!.sendReq(req)
                } else {
                    Toast.makeText(this@LoginActivity, "用户没有安装微信", Toast.LENGTH_SHORT).show()
                    finish()
                }
            }
        })
    }

    private fun isWXAppInstalledAndSupported(): Boolean {
        val msgApi = WXAPIFactory.createWXAPI(this, null)
        msgApi.registerApp(MainHttpConsts.WX_APP_ID)
        return (msgApi.isWXAppInstalled)
    }

    private fun Login() {
        phoneNum = edit_phone!!.text.toString().trim { it <= ' ' }
        if (TextUtils.isEmpty(phoneNum)) {
            edit_phone!!.error = resources.getString(R.string.login_input_phone)
            edit_phone!!.requestFocus()
            return
        }
        if (!ValidatePhoneUtil.validateMobileNumber(phoneNum)) {
            edit_phone!!.error = resources.getString(R.string.login_phone_error)
            edit_phone!!.requestFocus()
            return
        }
        pwd = edit_pwd!!.text.toString().trim { it <= ' ' }
        if (TextUtils.isEmpty(pwd)) {
            edit_pwd!!.error = resources.getString(R.string.login_input_pwd)
            edit_pwd!!.requestFocus()
            return
        }
        if (pwd!!.length < 6 || pwd!!.length > 16) {
            edit_pwd!!.error = resources.getString(R.string.invalid_password)
            edit_pwd!!.requestFocus()
            return
        }
        HttpLogin()
    }

    private fun HttpLogin() {
        Thread(Runnable {
            try {
                val returnData = MainHttpUtils.getInstance().Login(phoneNum, pwd)
                if (returnData == null) {
                    mHandle.sendEmptyMessage(0)
                    return@Runnable
                }
                val jsonObject = JSONObject(returnData)
                if (jsonObject != null && jsonObject.getInt("code") == 1) {
                    val data = jsonObject.getString("data")
                    if (!TextUtils.isEmpty(data)) {
                        val userInfo = GsonUtils.parseJObject(data, UserInfo::class.java)
                        if (userInfo != null) {
                            instance.token = userInfo.token
                            instance.nickName = userInfo.user_nickname
                            instance.phoneNum = phoneNum
                            instance.userId = userInfo.id
                            instance.isVip = if (userInfo.is_vip == 1) true else false
                            instance.userinfo = userInfo
                            instance.isLogin=true
                            phoneNum?.let {
                                applicationContext.putPrefString("account", it)
                            }
                            pwd?.let {
                                applicationContext.putPrefString("password", it)
                            }
                        } else {
                            mHandle.sendEmptyMessage(0)
                            return@Runnable
                        }
                    } else {
                        mHandle.sendEmptyMessage(0)
                        return@Runnable
                    }
                    mHandle.sendEmptyMessage(1)
                } else {
                    val msg = Message.obtain()
                    msg.obj = jsonObject.getString("msg")
                    msg.what = 2
                    mHandle.sendMessage(msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }).start()
    }

    private fun HttpGetBookSource() {
        Thread(Runnable {
            try {
                val returnData = MainHttpUtils.getInstance().GetBookSource()
                if (returnData == null) {
                    return@Runnable
                }
                val jsonObject = JSONObject(returnData)
                if (jsonObject != null && jsonObject.getInt("code") == 1) {
                    val data = jsonObject.getString("data")
                    if (TextUtils.isEmpty(data)) return@Runnable
                    val bookSourceList = BookSourceManager.GetInstance().importBookSourceFromJson(data)
                    if (bookSourceList == null || bookSourceList.size == 0) {
                        mHandle.sendEmptyMessage(3)
                        return@Runnable
                    } else {
                        BookSourceManager.GetInstance().AddBookSources(bookSourceList)
                    }
                } else {
                    val msg = Message.obtain()
                    msg.obj = jsonObject.getString("msg")
                    msg.what = 2
                    mHandle.sendMessage(msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }).start()
    }

    private fun HttpGetSearckKey() {
        Thread(Runnable {
            try {
                val returnData = MainHttpUtils.getInstance().GetSearchKeys(instance.token)
                        ?: return@Runnable
                val jsonObject = JSONObject(returnData)
                if (jsonObject != null && jsonObject.getInt("code") == 1) {
                    val data = jsonObject.getString("data")
                    if (TextUtils.isEmpty(data)) {
                        return@Runnable
                    }
                    val historyKeys = GsonUtils.parseJArray(data, String::class.java)
                    SearchBookManager.GetInstance().AddHistoryKeys(historyKeys)
                } else {
                    val msg = Message.obtain()
                    msg.obj = jsonObject.getString("msg")
                    msg.what = 2
                    mHandle.sendMessage(msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }).start()
    }

    private fun HttpGetBookMark() {
        Thread(Runnable {
            try {
                val returnData = MainHttpUtils.getInstance().GetBooks(1, MyApplication.instance.token)
                        ?: return@Runnable
                val jsonObject = JSONObject(returnData)
                if (jsonObject != null && jsonObject.getInt("code") == 1) {
                    val data = jsonObject.getString("data")
                    if (TextUtils.isEmpty(data)) return@Runnable
                    val jObject = JSONObject(data)
                    val lists = jObject.getString("lists")
                    val jsonArray = JSONArray(lists)
                    for (i in 0 until jsonArray.length()) {
                        val json = jsonArray[i] as JSONObject
                        val book = Book()
                        book.name = json.getString("name")
                        book.bookUrl = json.getString("url")
                        book.tocUrl = json.getString("chapter_url")
                        book.latestChapterTitle = json.getString("final_refresh_data")
                        book.coverUrl = json.getString("cover_url")
                        book.author = json.getString("author")
                        book.intro = json.getString("introduce")
                        book.origin = json.getString("origin")
                        book.originName = json.getString("origin_name")
                        book.charset = json.getString("charset")
                        book.group = 1
                        book.durChapterTitle = json.getString("dur_chapter_title")
                        book.durChapterIndex = json.getInt("dur_chapter_index")
                        book.durChapterPos = json.getInt("dur_chapter_pos")
                        book.order=i
                        BookManager.GetInstance().AddBook(book)
                    }
                } else {
                    val msg = Message.obtain()
                    msg.obj = jsonObject.getString("msg")
                    msg.what = 2
                    mHandle.sendMessage(msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }).start()
    }

    private fun HttpGetPageAd() {
        Thread(Runnable {
            try {
                val returnData = MainHttpUtils.getInstance().GetPageViewAdH5()
                if (returnData == null) {
                    return@Runnable
                }
                val jsonObject = JSONObject(returnData)
                if (jsonObject != null && jsonObject.getInt("code") == 1) {
                    val data = jsonObject.getString("data")
                    if (TextUtils.isEmpty(data)) return@Runnable
                    MyApplication.instance.pageH5=GsonUtils.parseJObject(jsonObject.getString("data"), H5AdBean::class.java)
                    //MyApplication.instance.pageAdList = GsonUtils.parseJArray(jsonObject.getString("data"), AdBean::class.java)
                } else {
                    val msg = Message.obtain()
                    msg.obj = jsonObject.getString("msg")
                    msg.what = 2
                    mHandle.sendMessage(msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }).start()
    }

    private val mHandle: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                0 -> Toast.makeText(applicationContext, resources.getString(R.string.login_http_fail), Toast.LENGTH_SHORT).show()
                1 -> {
                    //Toast.makeText(applicationContext, resources.getString(R.string.login_auth_success), Toast.LENGTH_SHORT).show()
                    //HttpGetBookSource()
                    HttpGetSearckKey()
                    HttpGetBookMark()
                    HttpGetPageAd()
                    val intent = Intent(applicationContext, MainActivity::class.java)
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
                    startActivity(intent)
                }
                2 -> Toast.makeText(applicationContext, msg.obj.toString(), Toast.LENGTH_SHORT).show()
                3 -> Toast.makeText(applicationContext, resources.getString(R.string.booksource_http_fail), Toast.LENGTH_SHORT).show()
                4 -> Toast.makeText(applicationContext, resources.getString(R.string.booksource_http_success), Toast.LENGTH_SHORT).show()
                5 -> Toast.makeText(applicationContext, resources.getString(R.string.booksource_history_key_fail), Toast.LENGTH_SHORT).show()
                6 -> Toast.makeText(applicationContext, resources.getString(R.string.booksource_history_key_success), Toast.LENGTH_SHORT).show()
            }
        }
    }
}